package cn.lanqiao.web.controller;

import cn.lanqiao.common.entity.Admin;
import cn.lanqiao.common.utile.Result;
import cn.lanqiao.system.service.AdminService;
import cn.lanqiao.web.utils.JwtUtils;
import cn.lanqiao.web.utils.RedisUtil;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${redis.keys.login-tokens}")
    private String loginToken ;

    @Value("${redis.keys.login-times}")
    private String loginTimes ;

    @Value("${redis.expire-time.token-expire_time}")
    private Long expireTime ;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, String captcha){
        try {
            if(!redisUtil.hasKey("redisCaptcha")){
                return Result.ok("验证码过期，请重新输入",4004);
            }
            // 获取redis中的验证码
            String redisCode = String.valueOf(redisUtil.get("redisCaptcha"));
            System.out.println("redisCode = " + redisCode);
            System.out.println("captcha = " + captcha);
            //校验验证码是否正确
            if(!redisCode.equals(captcha.trim().toLowerCase())){
                return Result.ok("验证码错误，请重新输入",4005);
            }
            Admin admin = adminService.login(username,password) ;
            if(admin != null){//用户名密码正确
                //生成 token
                String token = JwtUtils.getJwtToken(admin) ;
                System.out.println("token : " + token);
                //保存token到redis
                String key = loginToken + admin.getUsername() ;
                redisUtil.set(key,token,expireTime) ;
                //返回给前端页面
                Result r = new Result();
                r.setCode(2000);
                r.setData(token);
                r.setAdmin(admin);
                return r ;
            }else{
                //密码错误
                String key = loginTimes + admin.getUsername() ;
                if(redisUtil.hasKey(key)){
                    int time = Integer.parseInt(redisUtil.get(key).toString()) ;
                    if((time + 1) == 3){
                        return Result.ok("您登录次数太频繁，请过一会再试",4005) ;
                    }
                    //获取之前的过期时间
                    long expire = redisUtil.getExpire(key) ;
                    redisUtil.del(key);
                    redisUtil.set(key,time+1,expire) ;
                }else{
                    redisUtil.set(key,1,60*10) ;
                }
                return Result.ok("用户名密码错误",4000) ;
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("系统异常");
        }
    }

    //产生验证码
    @RequestMapping("/captcha")
    public void captcha(HttpServletResponse response) throws Exception {

/*        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);*/

        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        // 验证码存入redis
        redisUtil.set("redisCaptcha", specCaptcha.text().toLowerCase(), 60);
        // 输出图片流
        specCaptcha.out(response.getOutputStream());
    }

    @RequestMapping("/getCode")
    public Result getCode(){
        //产生验证码
        String code = UUID.randomUUID().toString().replaceAll("-","").substring(0,4) ;
        //生成uuid
        String key = UUID.randomUUID().toString().replaceAll("-","").substring(0,6) ;
        //保存到redis
        redisUtil.set(key,code,60) ;
        Map map = new HashMap() ;
        map.put("key",key) ;
        map.put("code",code) ;
        return Result.ok(map) ;

    }
}
